//
//  HomeViewController.m
//  share_business
//
//  Created by 吴于凌 on 2017/8/26.
//  Copyright © 2017年 wyl. All rights reserved.
//

#import "HomeViewController.h"
#import "UIButton+ImageTitleSpacing.h"
#import "JYCarousel.h"

#import "HomeNewsCollectionViewCell.h"
#import "HomeTodayGoodsCollectionViewCell.h"
#import "HomeGoodsCollectionViewCell.h"
#import "HomeShareGoodsCollectionViewCell.h"

#import "HomeItemHeaderCell.h"
#import "HomeTodayHeaderCell.h"
#import "GoodsDetailViewController.h"

#import "GoodsListViewController.h"

#import "GoodsService.h"
const static int ad_height = 180 ;
@interface HomeViewController ()<UITextFieldDelegate,JYCarouselDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,HomeTodayGoodsCollectionViewCellDelegate>

@property (nonatomic, strong) BaseCollectionview *collectionView;
@property (nonatomic,strong) UICollectionViewFlowLayout *flowLayout ;

@property (nonatomic,strong)  JYCarousel *carouselView ;
@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    NSMutableArray *arr  = [NSMutableArray array];
    [arr addObject:@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1505062820730&di=09df4f5452a956b0c150b6d0bd8d958f&imgtype=0&src=http%3A%2F%2Fdown1.sucaitianxia.com%2Fpsd02%2Fpsd158%2Fpsds28170.jpg"];
     [arr addObject:@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1505062820730&di=09df4f5452a956b0c150b6d0bd8d958f&imgtype=0&src=http%3A%2F%2Fdown1.sucaitianxia.com%2Fpsd02%2Fpsd158%2Fpsds28170.jpg"];
     [arr addObject:@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1505062820730&di=09df4f5452a956b0c150b6d0bd8d958f&imgtype=0&src=http%3A%2F%2Fdown1.sucaitianxia.com%2Fpsd02%2Fpsd158%2Fpsds28170.jpg"];
    [self setHeaderView:arr];
    [self initCollectionView];
    
    @weakify(self);
    [GoodsService getHomeIndex:^(id data) {
        @strongify(self);
        
        if (data) {
            HomeModel *model = data ;
            NSLog(@"model === %@",model);
        }
    } failure:^(NSError *error) {
        
    }];
  
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setTopTitleView];
    [self topLeftItemButton:ImageNamed(@"home_topTitle_left") title:@"扫一扫"];
    [self topRightItemButton:ImageNamed(@"home_message") image2:nil title1:@"消息" title2:nil];
  
}

-(void)setTopTitleView{
    UIView *titleViewM = [[UIView alloc]initWithFrame:CGRectMake(0, 27, APPWIDTH - 72*2, 35)];
    UIImageView *searchView = [BSWidget commonImageViewWithFrame:CGRectMake(10, 0, 17, 18) image:ImageNamed(@"home_search_tip")];
    searchView.centerY = 35 / 2 ;
    
    UITextField *searchBar = [[UITextField alloc] init];
    searchBar.delegate = self;
    searchBar.returnKeyType = UIReturnKeySearch;
    searchBar.frame = CGRectMake(searchView.maxX +3, 0, APPWIDTH - 72*2, 35);
    searchBar.placeholder = @" 搜索全部";
    searchBar.font =[UIFont systemFontOfSize:14];
    searchBar.backgroundColor = [UIColor clearColor];
    searchBar.userInteractionEnabled = YES ;
    [titleViewM setBorder:0 cornerRadius:4];
    
    titleViewM.backgroundColor= [UIColor colorWithHexString:COLOR_LIGHT_GRAY];
    [titleViewM addSubview:searchBar];
    [titleViewM addSubview:searchView];
    self.navigationItem.titleView = titleViewM;
    
//    UITapGestureRecognizer*tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickGoodsList)];
//    [searchBar addGestureRecognizer:tapGesture];
    
}
// 获得焦点
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    GoodsListViewController *vc  = [[GoodsListViewController alloc]init];
    vc.hidesBottomBarWhenPushed = YES ;
    [self.navigationController pushViewController:vc animated:NO];
    return YES;
}
-(void)clickGoodsList{
//    GoodsListViewController *vc  = [[GoodsListViewController alloc]init];
//    vc.hidesBottomBarWhenPushed = YES ;
//    [self.navigationController pushViewController:vc animated:YES];
}

-(void)initCollectionView{
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout.headerReferenceSize = CGSizeMake(APPWIDTH,ad_height);//头部大小
    _collectionView = [[BaseCollectionview alloc]initWithFrame:CGRectMake(0, 0, APPWIDTH, APPHEIGHT) collectionViewLayout:self.flowLayout];
    _collectionView.backgroundColor =[UIColor whiteColor];
    _collectionView.showsVerticalScrollIndicator =  NO;
    //定义每个UICollectionView 横向的间距
    self.flowLayout.minimumLineSpacing = 0;
    //定义每个UICollectionView 纵向的间距
    self.flowLayout.minimumInteritemSpacing = 0;
    //定义每个UICollectionView 的边距距
    self.flowLayout.sectionInset = UIEdgeInsetsMake(0, -0.25, 0, -0.25);//上左下右
    
    //注册cell和ReusableView（相当于头部）
    [_collectionView registerClass:[HomeNewsCollectionViewCell class] forCellWithReuseIdentifier:@"HomeNewsCollectionViewCell"];
    
    [_collectionView registerClass:[HomeTodayGoodsCollectionViewCell class] forCellWithReuseIdentifier:@"HomeTodayGoodsCollectionViewCell"];
    
    [_collectionView registerClass:[HomeShareGoodsCollectionViewCell class] forCellWithReuseIdentifier:@"HomeShareGoodsCollectionViewCell"];
    
    [_collectionView registerClass:[HomeGoodsCollectionViewCell class] forCellWithReuseIdentifier:@"HomeGoodsCollectionViewCell"];
    
    
    [_collectionView registerClass:[HomeItemHeaderCell class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeItemHeaderCell"];
    
    [_collectionView registerClass:[HomeTodayHeaderCell class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeTodayHeaderCell"];
    
    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    //设置代理
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    //自适应大小
    _collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    [self.view addSubview:self.collectionView];
}

//添加轮播图
- (void)setHeaderView:(NSMutableArray *)array{
    __weak typeof(self) weakSelf = self;
    [self.carouselView removeFromSuperview];
    self.carouselView = nil ;
    self.carouselView = [[JYCarousel alloc] initWithFrame:CGRectMake(0, 0, ViewWidth(self.view), ad_height) configBlock:^JYConfiguration *(JYConfiguration *carouselConfig) {
        //配置指示器类型
        carouselConfig.pageContollType = MiddlePageControl;
        //配置轮播时间间隔
        carouselConfig.interValTime = 3;
        //图片显示方式
        carouselConfig.contentMode = UIViewContentModeScaleAspectFit ;
        //配置动画方向
        carouselConfig.currentPageTintColor = [UIColor orangeColor];
        return carouselConfig;
    } clickBlock:^(NSInteger index) {
        //点击imageView回调方法
        
    }];
    self.carouselView.tag = 101 ;
    //开始轮播
    [self.carouselView startCarouselWithArray:array];
    
    UIImageView *view = [BSWidget commonImageViewWithFrame:CGRectMake(0, ad_height-13, APPWIDTH, 13) image:ImageNamed(@"bg_top_ad_bottom")];
    view.contentMode = UIViewContentModeScaleToFill ;
    
    [self.carouselView addSubview:view];
    [self.collectionView reloadData];
}


#pragma mark UICollectionView相关
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else if(section == 1) {
        
        return  1  ;
    }else if(section == 2) {
        return  4 ;
    }else if (section == 3){
        return 3 ;
        
    }
    return 0 ;
}

//每个UICollectionView大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    //最新活动
    if (indexPath.section == 0) {
        return CGSizeMake(APPWIDTH, 70) ;
        //今日特价
    }else if(indexPath.section == 1){
        return  CGSizeMake(APPWIDTH, 220);
        //生活范
    }else if(indexPath.section == 2){
        return  CGSizeMake(APPWIDTH / 2, 160);
        // 品质控
    }else if(indexPath.section == 3){
        return  CGSizeMake(APPWIDTH,250);
    }
    return  CGSizeMake(0, 0);
}
#pragma mark 定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 4;
}
//头部高度
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    //最新活动(广告)
    if (section == 0) {
        return CGSizeMake(APPWIDTH, 180) ;
        //今日特价
    }else if(section == 1){
        return CGSizeMake(APPWIDTH, 50);
        //生活范
    }else if(section == 2){
        return CGSizeMake(APPWIDTH, 60);
        // 品质控
    }else {
        return CGSizeMake(APPWIDTH, 60);
    }
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeMake(0, 0);
}
#pragma mark 每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
        //最新活动
    if (indexPath.section == 0) {
        static NSString *identify = @"HomeNewsCollectionViewCell";
        HomeNewsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
        
        return cell;
            //今日特价
    }else if(indexPath.section == 1) {
        static NSString *identify = @"HomeTodayGoodsCollectionViewCell";
        HomeTodayGoodsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
        cell.delegate =self ;
        [cell setModel:nil];
        return cell;
          //生活范
    }else if(indexPath.section == 2){
        static NSString *identify = @"HomeGoodsCollectionViewCell";
        HomeGoodsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
        
        return cell;
        // 品质控
    }else {
        static NSString *identify = @"HomeShareGoodsCollectionViewCell";
        HomeShareGoodsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
        return cell;
    }
}

#pragma mark 头部显示的内容
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    //如果是头视图
    if ([kind isEqualToString:UICollectionElementKindSectionHeader] && indexPath.section == 0) {
        UICollectionReusableView *header=[collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
        if (![header viewWithTag:101]) {
            [header addSubview:self.carouselView];
        }
        return header;
        
    } else if([kind isEqualToString:UICollectionElementKindSectionHeader] && indexPath.section == 1){
       HomeTodayHeaderCell *header=[collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"HomeTodayHeaderCell" forIndexPath:indexPath];
        header.backgroundColor = [UIColor colorWithHexString:@"#f4f4f4"];
 
        return header;
    }else if([kind isEqualToString:UICollectionElementKindSectionHeader] && indexPath.section == 2){
        HomeItemHeaderCell *header=[collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"HomeItemHeaderCell" forIndexPath:indexPath];
        [header setType:0];
        return header;
    }else if([kind isEqualToString:UICollectionElementKindSectionHeader] && indexPath.section == 3){
        HomeItemHeaderCell *header=[collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"HomeItemHeaderCell" forIndexPath:indexPath];
         [header setType:1];
        return header;
    }
    
    return nil;
}
#pragma mark UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    GoodsDetailViewController *vc = [[GoodsDetailViewController alloc]init];
    vc.hidesBottomBarWhenPushed = YES ;
    [self.navigationController pushViewController:vc animated:YES];
}



//左边按钮
-(void)leftAction:(UIButton *)button{
    
 }
-(void )todayClickCallBack{
    GoodsDetailViewController *vc = [[GoodsDetailViewController alloc]init];
    vc.hidesBottomBarWhenPushed = YES ;
    [self.navigationController pushViewController:vc animated:YES];
}

@end
